package com.tidy.seed.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tidy.seed.admin.system.dto.LoginUserDTO;
import com.tidy.seed.admin.system.dto.RegisterUserDTO;
import com.tidy.seed.admin.system.entity.Role;
import com.tidy.seed.admin.system.entity.User;
import com.tidy.seed.admin.system.mapper.MenuMapper;
import com.tidy.seed.admin.system.mapper.UserMapper;
import com.tidy.seed.admin.system.service.UserRoleService;
import com.tidy.seed.admin.system.service.UserService;
import com.tidy.seed.admin.system.vo.GetUserMenuVO;
import com.tidy.seed.admin.system.vo.LoginResponseVO;
import com.tidy.seed.admin.system.vo.UserRoleVO;
import com.tidy.seed.admin.system.vo.UserVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tidy.seed.util.JwtUtils;
import com.tidy.seed.util.UserThreadLocal;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HZ-ZY
 * @since 2025-08-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private MenuMapper menuMapper;


    public Boolean register(RegisterUserDTO dto) {
        boolean isExistsUser = userMapper.exists(Wrappers.<User>query().like("username", dto.getUsername()));
        if (isExistsUser) return false;
        //创建User对象
        User user = new User();

        //加密密码
        String password = dto.getPassword();
//        加密密码
//        String salt = user.getSalt();
//        String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());

        user.setUsername(dto.getUsername());
        user.setPassword(password);

        userMapper.insert(user);
        return true;
    }

    public LoginResponseVO login(LoginUserDTO dto) {

        // 1. 通过用户名查询用户
        User user = userMapper.selectOne(Wrappers.<User>query().eq("username", dto.getUsername()));
        // 2. 判断用户是否存在
        if (user == null) return null; // 用户不存在，返回null

        if (!Objects.equals(user.getPassword(), dto.getPassword())) return null; // 密码不正确，返回null
        // 4. 密码正确，生成并返回token
        LoginResponseVO loginResponseVO = new LoginResponseVO();
        loginResponseVO.setUser(user);
        loginResponseVO.setToken(JwtUtils.createJwt(user));
        return loginResponseVO;
    }

    @Override
    public List<UserVO> findPage(Integer pageNum, Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        Page<User> userPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);
        //用foreach循环为每个用户设置角色信息
        List<User> userList = userPage.getRecords(); // 获取当前页用户列表
        List<Integer> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
        System.out.println(userIds);
        List<UserRoleVO> roleMap = userRoleService.findRolesByUserIds(userIds);
        List<UserVO> userVoList = new ArrayList<>();
        for (User user : userList) { // 遍历每个用户
            UserVO userVo = new UserVO();
            userVo.setId(user.getId());
            userVo.setUsername(user.getUsername());
            userVo.setPassword(user.getPassword());
            userVo.setNickname(user.getNickname());
            userVo.setEmail(user.getEmail());
            userVo.setPhone(user.getPhone());
            userVo.setAddress(user.getAddress());
            userVo.setAvatar(user.getAvatar());
            userVo.setBalance(user.getBalance());
            userVo.setStatus(user.getStatus());
            userVo.setSuperId(user.getSuperId());
            userVo.setCreateAt(user.getCreateAt());
            userVo.setUpdateAt(user.getUpdateAt());
            List<Role> roles = roleMap.stream().filter(roleVo -> Objects.equals(roleVo.getUserId(), user.getId()))
                    .map(UserRoleVO::getRole)
                    .flatMap(List::stream) //合并为扁平列表：用 flatMap(List::stream) 转换后再收集。
                    .collect(Collectors.toList());
            userVo.setRoleList(roles);
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public List<GetUserMenuVO> getUserMenu() {
        List<GetUserMenuVO> rawList = menuMapper.getUserMenu(UserThreadLocal.getUserId());
        // 利用LinkedHashMap保持顺序，key为菜单id，去重
        Map<Integer, GetUserMenuVO> menuMap = new LinkedHashMap<>();
        for (GetUserMenuVO menu : rawList) {
            // 如果已存在，覆盖(你也可以选择跳过)
            menuMap.put(menu.getId(), menu);
        }
        // 遍历原始列表，找出所有按钮合并到对应父菜单btnTags
        for (GetUserMenuVO menu : rawList) {
            if (menu.getMenuType() != null && menu.getMenuType() == 2) { // 按钮
                Integer parentId = menu.getParentId();
                if (parentId != null && menuMap.containsKey(parentId)) {
                    GetUserMenuVO parentMenu = menuMap.get(parentId);

                    Set<String> btnTagSet = new HashSet<>(Arrays.asList(parentMenu.getBtnTags()));
                    btnTagSet.add(menu.getMenuKey());
                    parentMenu.setBtnTags(btnTagSet.toArray(new String[0]));
                }
            }
        }
        // 过滤掉按钮，只返回菜单和目录
        return menuMap.values().stream()
                .filter(menu -> menu.getMenuType() != null && menu.getMenuType() != 2)
                .collect(Collectors.toList());
    }

}
